var oWebControl = null;
var accessToken = "";
import Vue from "vue.min.js";
/**
 * video 初始化及配置
 * @param {*video挂载的dom id} id
 * @param {*连接成功的回调} cbConnectSuccess
 * @param {*连接报错的回调} cbConnectError
 * @param {*连接关闭的回调} cbConnectClose
 */
export default function WebControlInit(id, cbConnectSuccess, cbConnectError, cbConnectClose) {
  return new WebControl({
    szPluginContainer: id,
    iServicePortStart: 14510, // 对应 LocalServiceConfig.xml 中的ServicePortStart值
    iServicePortEnd: 14519, // 对应 LocalServiceConfig.xml 中的ServicePortEnd值
    cbConnectSuccess: cbConnectSuccess,
    cbConnectError: cbConnectError,
    cbConnectClose: cbConnectClose,
  });
}
/**
 * 离开页面时调用 断开链接的方法
 * @param {*视频插件实例} oWebControl
 */
function WebControlDistory() {
  if (oWebControl != null) {
    oWebControl.JS_DestroyWnd().then(
      function () {
        console.log("JS_DestroyWnd");
      },
      function () {}
    );
    oWebControl.JS_StopService("window").then(function () {
      oWebControl.JS_Disconnect().then(
        function () {
          console.log("JS_Disconnect");
        },
        function () {}
      );
    });
  }
}
// 监听视频控件的事件
function cbIntegrationCallBack(oData) {
  app.showCBInfo(oData);
  if (oData.responseMsg.eventName === "FireTransFunction") {
    // 如果视频控件需要请求服务端数据，这里可以处理透传逻辑
  } else if (oData.responseMsg.eventName === "FireOcxVolumeInfo") {
    app.volumeInfo = oData.responseMsg.arguments;
  }
}

function cbConnectSuccess() {
  // 设置窗口控制回调
  oWebControl.JS_SetWindowControlCallback({
    cbIntegrationCallBack: cbIntegrationCallBack,
  });
  //创建视频窗口
  oWebControl
    .JS_StartService("window", {
      dllPath: "./chain/cloudTransform.dll",
    })
    .then(function () {
      oWebControl.JS_CreateWnd("playWnd", 900, 500).then(function () {
        console.log("JS_CreateWnd success");
        oWebControl.JS_RequestInterface({
          funcName: "GetOCXVersion",
        });
      });
    });
}

function cbConnectError() {
  console.log("cbConnectError");
  oWebControl = null;
  console.error("确认本地进程是否已安装并开启成功！");
}

function cbConnectClose(bNormalClose) {
  // 连接异常断开：bNormalClose = false
  // JS_Disconnect正常断开：bNormalClose = true
  console.log("cbConnectClose");
  oWebControl = null;
}

//销毁视频控件

window.onscroll = function () {
  if (oWebControl != null) {
    oWebControl.JS_Resize(900, 500);
  }
};
window.onresize = function () {
  if (oWebControl != null) {
    oWebControl.JS_Resize(900, 500);
  }
};

window.onunload = function () {
  try {
    oWebControl.JS_HideWnd();
    WebControlDistory();
  } catch (error) {
    console.error(error);
  }
};
window.onpagehide = function () {
  try {
    oWebControl.JS_HideWnd();
  } catch (error) {
    console.error(error);
  }
};
var limitStart = parseInt(
  new Date("2021-07-29T16:01:00").getTime() / 1000
).toString();
var limitEnd = parseInt(
  new Date("2021-07-29T17:01:30").getTime() / 1000
).toString();
/**
 * 预览界面支持隐藏的项
 */
var PMainAllClose = 16384; //全部关闭
var PMainAllRec = 512; //全部录像
var PMainAllSetting = 32768; //设置
var PMainAllSnap = 1024; //全部抓图
var PMainAspectRatio = 4096; //画面比例
var PMainFullScreen = 65536; //全屏
var PMainLayout = 8192; //布局
var PMainPtz = 2048; //云台
var PSubArticulation = 128; //清晰度
var PSubElecgrow = 64; //电子放大
var PSubFish = 1; //鱼眼
var PSubInstant = 32; //即时回放
var PSubRecord = 8; //录像
var PSubSnap = 4; //抓图
var PSubSound = 2; //声音
var PSubTalk = 16; //对讲
var PSubVideoParams = 256; //视频参数
var PMenuWiper = 131072; //雨刷
var PMenuCorridor = 262144; //走廊模式
var PMenuMotion = 524288; //移动侦测
var PMenuRight = 2097152; //右键菜单
var PMenuRule = 1048576; //智能规则
var PMainPage = 4194304; //预览分页码
/**
 * 回放界面支持隐藏的项
 */
var PBSubElecGrow = 16; //电子放大
var PBSubFish = 1; //鱼眼
var PBSubRecord = 8; //录像
var PBSubSnap = 4; //抓图
var PBSubSound = 2; //声音
var PBMainAllClose = 32768; //全部关闭
var PBMainAllSnap = 512; //全部抓图
var PBMainAspectRatio = 8192; //画面比例
var PBMainAllStop = 256; //全部关闭
var PBMainDownloader = 65536; //下载中心
var PBMainFullScreen = 262144; //全屏
var PBMainLayout = 16384; //布局
var PBMainScale = 1024; //倍速回放
var PBMainNext10s = 32; //前进10s
var PBMainPause = 128; //暂停
var PBMainPre10s = 64; //回退10s
var PBMainRecordType = 4096; //录像类型
var PBMainSetting = 131072; //设置
var PBMainSyncPlayBack = 524288; //同步回放
var PBMenuDownload = 2097152; //录像下载
var PBMenuPlay = 4194304; //播放/暂停
var PBMenuStop = 8388608; //停止
var PBMenuRight = 1048576; //右键菜单
var CfgOpenPlayKeepLive = 1; //打开PlayKeepLive
var CfgOpenTalkStatus = 2; //打开对讲状态

//var iPHideItem = PMenuRule+PMenuMotion+PMenuCorridor+PMenuWiper+PSubVideoParams+PSubArticulation+PSubElecgrow+PSubInstant+PSubTalk+PSubRecord+PSubSnap+PSubSound+PSubFish+PMainAllClose+PMainAllRec+PMainAllSnap+PMainAllSetting+PMainAspectRatio+PMainLayout+PMainPtz+PMainFullScreen;
//var iPBHideItem = PBMenuRight+PBMenuStop+PBMenuPlay+PBMenuDownload+PBSubSnap+PBSubSound+PBSubRecord+PBSubFish+PBSubElecGrow+PBMainPre10s+PBMainNext10s+PBMainPause+PBMainScale+PBMainFullScreen+PBMainAllClose+PBMainAllSnap+PBMainAllStop+PBMainSetting+PBMainAspectRatio+PBMainLayout+PBMainRecordType+PBMainSyncPlayBack+PBMainDownloader;

var iPHideItem = PMainPage;
var iPBHideItem = 0;
var iCfgItem = CfgOpenTalkStatus + CfgOpenPlayKeepLive;
var app = new Vue({
  el: "#app",
  data() {
    return {
      appKey: "",
      ezvizToken: "",
      accessToken: "",
      deviceSerial: "FN1234567",
      channelNo: 1,
      deviceClass: "0",
      startTime: "2023-04-25 13:08:30",
      endTime: "",
      volumeInfo: {
        index: -1,
        volumeSwitch: 0,
        volume: 0,
      },
      layout: 2,
      switchVideo: 0, // 0实时预览 1录像回放
      callbackMessage: "", //显示回调信息
      tips: "调用成功",
      successTip: false,
      tipsShow: false,
      boardName: "",
      localAppKeys: [],
      localEzvizTokens: [],
      localAccessTokens: [],
      labelId: "",
      status: 0,
      direction: 1,
      maskItemList: [
        {
          id: Date.now(),
          maskPosType: 1,
          maskPosx: 0,
          maskPosy: 0,
          maskWidth: 100,
          maskHeight: 100,
          isCover: false,
        },
      ],
      requestMessage: "",
    };
  },

  computed: {
    switchLineStyle: function () {
      if (this.switchVideo === 0) {
        return {
          transform: "translateX(0px)",
        };
      } else if (this.switchVideo === 1) {
        return {
          transform: "translateX(88px)",
        };
      } else if (this.switchVideo === 5) {
        return {
          transform: "translateX(176px)",
        };
      }
      return {
        transform: "translateX(264px)",
      };
    },
  },
  mounted: function () {
    this.initAppKey();
    this.initToken();
    this.initAccessToken();
    oWebControl = WebControlInit(
      "playWnd",
      cbConnectSuccess,
      cbConnectError,
      cbConnectClose
    );
  },
  methods: {
    onScrolling() {
      oWebControl && oWebControl.JS_Resize(900, 500);
    },
    generateUniqueId() {
      return (
        "id-" + Date.now() + "-" + Math.random().toString(36).substring(2, 9)
      );
    },
    addMaskItem() {
      this.maskItemList.push({
        id: this.generateUniqueId(),
        maskPosType: 1,
        maskPosx: 0,
        maskPosy: 0,
        maskWidth: 100,
        maskHeight: 100,
        isCover: false,
      });
    },
    delMaskItem(index) {
      this.maskItemList.splice(index, 1);
    },
    getEagleNodeList() {
      let res = {
        dataList: [
          {
            nodeId: "1",
            pointName: "AR鹰眼作战指挥中心",
            nodeName: "浙江嘉兴邻里中心鹰眼",
            deviceSerial: "AB12345",
            deviceName: "iDS-2DP1618ZIXS-D/440(AH7381843)",
            channelNo: 1,
            deviceType: 2,
          },
          {
            nodeId: "1",
            pointName: "AR鹰眼作战指挥中心",
            nodeName: "180度普通鹰眼",
            deviceSerial: "AB12346",
            deviceName: "iDS-2DP1618ZIXS-D/440(AF2261155)",
            channelNo: 2,
            deviceType: 4,
          },
        ],
      };
      oWebControl.JS_RequestInterface({
        funcName: "EagleNodeList",
        arguments: encodeURI(JSON.stringify(res)),
      });
    },
    initAppKey() {
      let localAppKeys = localStorage.getItem("localAppKeys");
      if (localAppKeys) {
        localAppKeys = JSON.parse(localAppKeys);
        if (Array.isArray(localAppKeys) && localAppKeys.length) {
          this.localAppKeys = localAppKeys;
          this.appKey = localAppKeys[0];
        }
      }
    },
    setLocalAppKeys() {
      let localAppKeys = localStorage.getItem("localAppKeys") || "[]";
      localAppKeys = JSON.parse(localAppKeys);
      const index = localAppKeys.findIndex((_) => _ === this.appKey);
      if (index > -1) {
        localAppKeys.splice(index, 1);
      } else {
        if (localAppKeys.length === 10) {
          localAppKeys.pop();
        }
      }
      localAppKeys.unshift(this.appKey);
      this.localAppKeys = localAppKeys;
      localStorage.setItem("localAppKeys", JSON.stringify(localAppKeys));
    },
    initToken() {
      let localEzvizTokens = localStorage.getItem("localEzvizTokens");
      if (localEzvizTokens) {
        localEzvizTokens = JSON.parse(localEzvizTokens);
        if (Array.isArray(localEzvizTokens) && localEzvizTokens.length) {
          this.localEzvizTokens = localEzvizTokens;
          this.ezvizToken = localEzvizTokens[0];
        }
      }
    },
    setLocalToken() {
      let localEzvizTokens = localStorage.getItem("localEzvizTokens") || "[]";
      localEzvizTokens = JSON.parse(localEzvizTokens);
      const index = localEzvizTokens.findIndex((_) => _ === this.ezvizToken);
      if (index > -1) {
        localEzvizTokens.splice(index, 1);
      } else {
        if (localEzvizTokens.length === 10) {
          localEzvizTokens.pop();
        }
      }
      localEzvizTokens.unshift(this.ezvizToken);
      this.localEzvizTokens = localEzvizTokens;
      localStorage.setItem(
        "localEzvizTokens",
        JSON.stringify(localEzvizTokens)
      );
    },
    initAccessToken() {
      let localAccessTokens = localStorage.getItem("localAccessTokens");
      if (localAccessTokens) {
        localAccessTokens = JSON.parse(localAccessTokens);
        if (Array.isArray(localAccessTokens) && localAccessTokens.length) {
          this.localAccessTokens = localAccessTokens;
          this.accessToken = localAccessTokens[0];
        }
      }
    },
    setLocalAccessTokens() {
      let localAccessTokens = localStorage.getItem("localAccessTokens") || "[]";
      localAccessTokens = JSON.parse(localAccessTokens);
      const index = localAccessTokens.findIndex((_) => _ === this.accessToken);
      if (index > -1) {
        localAccessTokens.splice(index, 1);
      } else {
        if (localAccessTokens.length === 10) {
          localAccessTokens.pop();
        }
      }
      localAccessTokens.unshift(this.accessToken);
      this.localAccessTokens = localAccessTokens;
      localStorage.setItem(
        "localAccessTokens",
        JSON.stringify(localAccessTokens)
      );
    },
    switchTo: function (num) {
      let self = this;
      this.switchVideo = num;
      if (oWebControl) {
        oWebControl
          .JS_RequestInterface({
            funcName: "ChangeModel",
            arguments: encodeURI(
              JSON.stringify({
                model: num,
              })
            ),
          })
          .then(function (oData) {
            self.playVideo();
          });
      }
    },
    sendRequest() {
      let self = this;
      try {
        const params = JSON.parse(self.requestMessage);
        oWebControl.JS_RequestInterface(params).then(function (oData) {
          console.log(JSON.stringify(oData.responseMsg));
          self.showCBInfo(oData.responseMsg);
        });
      } catch (error) {
        self.showTips(false, "请输入正确的JSON请求参数");
      }
    },
    volumnChange() {
      let self = this;
      let args = { ...this.volumeInfo };
      args.volumeSwitch = +args.volumeSwitch;
      oWebControl
        .JS_RequestInterface({
          funcName: "OperationVolume",
          arguments: encodeURI(JSON.stringify(args)),
        })
        .then(function (oData) {
          console.log(JSON.stringify(oData.responseMsg));
          self.showCBInfo(oData.responseMsg);
        });
    },
    syncVolumn() {
      let self = this;
      oWebControl
        .JS_RequestInterface({
          funcName: "GetVolumeInfo",
          arguments: encodeURI(
            JSON.stringify({
              index: this.volumeInfo.index,
            })
          ),
        })
        .then(function (oData) {
          console.log(JSON.stringify(oData.responseMsg));
          self.showCBInfo(oData.responseMsg);
        });
    },
    startTalk() {
      let self = this;
      oWebControl
        .JS_RequestInterface({
          funcName: "StartTalk",
          arguments: encodeURI(
            JSON.stringify({
              deviceSerial: self.deviceSerial,
              channelNo: self.channelNo,
              index: -1,
              talkMode: 1,
            })
          ),
        })
        .then(function (oData) {
          console.log(JSON.stringify(oData.responseMsg));
        });
    },
    stopTalk() {
      oWebControl
        .JS_RequestInterface({
          funcName: "StopTalk",
          arguments: {},
        })
        .then(function (oData) {
          console.log(JSON.stringify(oData.responseMsg));
        });
    },
    updateLabelStatus() {
      let self = this;
      oWebControl
        .JS_RequestInterface({
          funcName: "UpdateLabelStatus",
          arguments: encodeURI(
            JSON.stringify({
              labelId: self.labelId,
              status: self.status,
            })
          ),
        })
        .then(function (oData) {
          console.log(JSON.stringify(oData.responseMsg));
        });
    },
    updatePTZ(operation, direction) {
      let self = this;
      oWebControl
        .JS_RequestInterface({
          funcName: "PTZCtrl",
          arguments: encodeURI(
            JSON.stringify({
              direction,
              operation,
            })
          ),
        })
        .then(function (oData) {
          console.log(JSON.stringify(oData.responseMsg));
        });
    },
    updateMask(maskItem) {
      // maskItem.isCover = !maskItem.isCover;
      const opt = maskItem.isCover ? 1 : 0;
      oWebControl
        .JS_RequestInterface({
          funcName: "EagleWebMask",
          arguments: encodeURI(
            JSON.stringify({
              opt,
              posType: +maskItem.maskPosType,
              posx: +maskItem.maskPosx,
              posy: +maskItem.maskPosy,
              width: +maskItem.maskWidth,
              height: +maskItem.maskHeight,
              id: maskItem.id,
            })
          ),
        })
        .then(function (oData) {
          console.log(JSON.stringify(oData.responseMsg));
        });
    },
    /**
     * 设置视频初始化参数
     */
    initVideo: function () {
      let self = this;
      if (!self.appKey || !self.ezvizToken) {
        self.showTips(false, "请输入appkey和token");
        return;
      }
      // 初始化入参
      let argumentsPram = {
        layout: +self.layout,
        userName: "test@qq.com",
        waterMark: "1",
        iWndType: 0,
        intelligenceEnable: 1,
        isRecord: 1,
        iPreviewHideItem: iPHideItem,
        iPlayBackHideItem: iPBHideItem,
        iConfigItem: iCfgItem,
        isPtzRight: 1,
        isSetPos: 1,
        motionDetectEnable: 0,
        playBackAlarmOverlyingEnable: 0,
        token: self.accessToken,
        response: {
          code: 0,
          message: null,
          data: {
            appKey: self.appKey,
            ezvizToken: self.ezvizToken,
            videoLevel: 0,
            showMainTool: 1,
            showSubTool: 1,
            waterMark: "1",
            userName: "test@qq.com",
            EZVIZ_AuthAddr: "",
            EZVIZ_PlatAddr: "",
          },
        },
      };
      argumentsPram.eagleEyeAPIPrefix = "https://nissan.hik-cloud.com";
      console.log("初始化入参", argumentsPram);
      // 调用视频控件初始化方法
      oWebControl
        .JS_RequestInterface({
          funcName: "Init",
          arguments: encodeURI(JSON.stringify(argumentsPram)),
        })
        .then(function (oData) {
          self.showCBInfo(oData.responseMsg);
          self.showTips(true, "视频初始化成功！");
          self.setLocalAppKeys();
          self.setLocalToken();
          if (self.accessToken) {
            self.setLocalAccessTokens();
          }
        });
    },

    /**
     * 播放门店视频
     */
    playVideo: function () {
      let self = this;
      if (!self.deviceSerial || !self.channelNo) {
        self.showTips(false, "请输入设备序列号和通道号");
        return;
      }
      // 预览入参
      let argumentsPram = {
        response: {
          code: 0,
          message: null,
          data: {
            deviceSerial: self.deviceSerial,
            channelCode: self.channelNo,
            channelNo: +self.channelNo,
            codeIsEncrypt: 0,
            validateCode: "",
            deviceClass: self.deviceClass,
            deviceType: "",
            //deviceType:"10240",
            channelId: "2222222222",
            channelName: "channelNameTest",
            storeName: "storeName",
            storeId: "storeid",
            startTime: "2024-08-12 00:00:00",
            endTime: "",
            //Limited_start:limitStart,
            //Limited_end:limitEnd,
          },
        },
      };
      if (self.deviceClass === "1") {
        // 国标协议对应的两个字段
        argumentsPram.response.data.channelCode = self.channelNo;
      } else {
        // 海康协议对应的一个字段
        argumentsPram.response.data.channelNo = +self.channelNo;
      }
      // 回放时对应的两个字段
      if (this.switchVideo === 1) {
        if (this.startTime)
          argumentsPram.response.data.startTime = this.startTime;
        if (this.endTime) argumentsPram.response.data.endTime = this.endTime;
      }
      // 鹰眼模式
      if (this.switchVideo === 6) {
        argumentsPram.response.data = {
          Cameras: [
            {
              channelNo: 1,
              deviceSerial: self.deviceSerial,
              playWndIndex: 2, // 球机
              streamType: 1, // 清晰度 1高清，2标清
            },
            {
              channelNo: 2,
              deviceSerial: self.deviceSerial,
              playWndIndex: 1, // 全景
              streamType: 1,
            },
          ],
        };
      }
      console.log("预览/回放入参", argumentsPram);
      // 调用视频控件预览方法
      oWebControl
        .JS_RequestInterface({
          funcName:
            this.switchVideo === 0 || this.switchVideo == 5
              ? "StartPreview"
              : this.switchVideo === 6
              ? "MultiPreview"
              : "StartPlayback",
          arguments: encodeURI(JSON.stringify(argumentsPram)),
        })
        .then(function (oData) {
          self.showCBInfo(oData.responseMsg);
          self.showTips(true, "预览/回放成功！");
        });
    },
    /**
     * 设置事件回调信息
     */
    showCBInfo: function (message) {
      this.callbackMessage =
        this.callbackMessage + JSON.stringify(message) + "\n\n";
    },
    showTips: function (status, message) {
      let self = this;
      this.successTip = status;
      this.tips = message;
      this.tipsShow = true;
      setTimeout(function () {
        self.tipsShow = false;
      }, 1000);
    },
    /**
     * 隐藏视频
     */
    hideVideo: function () {
      oWebControl.JS_HideWnd();
    },
    /**
     * 显示视频
     */
    showVideo: function () {
      oWebControl.JS_ShowWnd();
    },
    /**
     * 获取窗口数
     */
    GetLayout: function () {
      let data = null;
      let self = this;

      oWebControl
        .JS_RequestInterface({
          funcName: "GetLayout",
          arguments: encodeURI(
            JSON.stringify({
              response: {
                code: 0,
                message: null,
                data: data,
              },
            })
          ),
        })
        .then(function (oData) {
          console.log(JSON.stringify(oData.responseMsg));
          self.showCBInfo(oData.responseMsg);
        });
    },
    /**
     * 抓图
     */
    CaptureJPGEx: function () {
      let data = null;
      let self = this;

      oWebControl
        .JS_RequestInterface({
          funcName: "CaptureJPGEx",
          arguments: encodeURI(
            JSON.stringify({
              response: {
                code: 0,
                message: null,
                data: data,
              },
            })
          ),
        })
        .then(function (oData) {
          console.log(JSON.stringify(oData.responseMsg));
          self.showCBInfo(oData.responseMsg);
        });
    },
    /**
     * 全部停止预览test
     */
    StopAllPreview: function () {
      oWebControl.JS_RequestInterface({
        funcName: "StopAllPreview",
      });
    },
    /**
     * 全部停止回放test
     */
    StopAllPlayback: function () {
      oWebControl.JS_RequestInterface({
        funcName: "StopAllPlayback",
      });
    },

    /**
     * 批量播放
     */
    StartMultiPreview: function () {
      let res = {
        response: {
          code: 0,
          data: {
            Cameras: [
              {
                channelId: "d9885df0aadf479d882be0c76e395572",
                storeName: "门店1",
                channelName: "通道1",
                channelNo: 1,
                deviceClass: "0",
                deviceSerial: "K12345678",
              },
              {
                channelId: "67df2d65661b498ab36715545b17d672",
                storeName: "门店1",
                channelName: "通道2",
                channelNo: 2,
                deviceClass: "0",
                deviceSerial: "K12345679",
              },
            ],
          },
          message: null,
        },
      };
      console.log(res);
      oWebControl.JS_RequestInterface({
        funcName: "MultiPreview",
        arguments: encodeURI(JSON.stringify(res)),
      });
    },

    alarmMsg() {
      let res = {
        request: {
          body: {
            alarmTypes: [10800, 0, 0, 0, 0],
            channelId: "066dde0465dd4abaab6afe355baf9d0b",
            endTime: "1621007999000",
            startTime: "1620921600000",
          },
          callBack: "GetAlarmMsgOrders",
          majorKey: "",
          method: "POST",
          storeId: "",
          url: "/videoplugin/message/getMessageByTypes",
        },
        response: {
          code: 0,
          message: null,
          data: [
            {
              alarmType: 10800,
              alarmName: "移动侦测报警",
              alarmTime: 1620921217000,
            },
            {
              alarmType: 10800,
              alarmName: "移动侦测报警",
              alarmTime: 1620920678000,
            },
          ],
          success: true,
        },
      };

      console.log(res);

      oWebControl.JS_RequestInterface({
        funcName: "TransFunctionResult",
        arguments: encodeURI(JSON.stringify(res)),
      });
      //.JS_RequestInterface({funcName: 'TransFunctionResult', arguments: {
      //  response: res
      //}})
    },

    SetLayout() {
      let self = this;
      oWebControl
        .JS_RequestInterface({
          funcName: "OPen_SetLayout",
          arguments: encodeURI(
            JSON.stringify({
              Layout: +self.layout,
            })
          ),
        })
        .then(function (oData) {
          console.log(JSON.stringify(oData.responseMsg));
        });
    },
  },
});
